import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../theme/keyboard_theme.dart' as theme;
import '../services/word_service.dart';
import '../services/translation_service.dart';
import 'dart:math';

class KeyboardController extends GetxController {
  final RxMap<String, bool> keyStates = <String, bool>{}.obs;
  final RxInt currentThemeIndex = 0.obs;
  
  // 打字练习相关状态
  final RxInt currentIndex = 0.obs;
  final RxString targetText = ''.obs;
  final RxList<bool> typedCharacters = <bool>[].obs;
  final RxList<bool> errorCharacters = <bool>[].obs;

  // 添加新的可观察变量
  final RxString currentTranslation = ''.obs;
  final RxInt translationX = 0.obs;
  final RxInt translationY = 0.obs;

  @override
  void onInit() async {
    super.onInit();
    // 初始化所有按键状态为未按下
    for (String keyLabel in keyMapping.values.toSet()) {
      keyStates[keyLabel] = false;
    }
    
    // 初始化单词服务
    await WordService.initialize();
    
    // 初始化翻译服务
    TranslationService.initialize();
    
    // 生成初始文本
    _generateNewText();
  }

  void onKeyEvent(dynamic event) {
    if (event is RawKeyEvent) {
      _handleRawKeyEvent(event);
    } else if (event is KeyEvent) {
      _handleKeyEvent(event);
    }
  }

  void _handleRawKeyEvent(RawKeyEvent event) {
    if (event is RawKeyDownEvent) {
      final keyLabel = _getKeyLabel(event.logicalKey);
      if (keyLabel != null) {
        keyStates[keyLabel] = true;
        keyStates.refresh();
      }
      
      final pressedChar = _getCharFromRawKey(event.logicalKey);
      if (pressedChar != null) {
        _handleCharacterInput(pressedChar);
      }
    } else if (event is RawKeyUpEvent) {
      final keyLabel = _getKeyLabel(event.logicalKey);
      if (keyLabel != null) {
        keyStates[keyLabel] = false;
        keyStates.refresh();
      }
    }
  }

  void _handleKeyEvent(KeyEvent event) {
    if (event is KeyDownEvent) {
      _handleKeyDown(event);
    } else if (event is KeyUpEvent) {
      _handleKeyUp(event);
    }
  }

  void _handleKeyDown(KeyEvent event) {
    // 获取键码
    final keyCode = event.logicalKey.keyId;
    
    // 更新键盘状态
    String? keyLabel = keyMapping[event.logicalKey];
    if (keyLabel != null) {
      keyStates[keyLabel] = true;
      // 同步特殊键状态
      if (keyLabel == 'SHIFT') keyStates['SHIFT'] = true;
      if (keyLabel == 'CTRL') keyStates['CTRL'] = true;
      if (keyLabel == 'ALT') keyStates['ALT'] = true;
    }

    // 处理打字练习逻辑
    String? pressedChar = _getCharFromKey(event.logicalKey);
    if (pressedChar != null && currentIndex.value < targetText.value.length) {
      debugPrint('Pressed char: $pressedChar, target: ${targetText.value[currentIndex.value]}');
      
      if (pressedChar.toLowerCase() == targetText.value[currentIndex.value].toLowerCase()) {
        // 输入正确
        typedCharacters[currentIndex.value] = true;
        errorCharacters[currentIndex.value] = false;
      } else {
        // 输入错误
        typedCharacters[currentIndex.value] = false;
        errorCharacters[currentIndex.value] = true;
      }
      
      currentIndex.value++;
      
      // 如果当前文本已经完成，生成新的文本
      if (currentIndex.value >= targetText.value.length) {
        _generateNewText();
      }
    }

    // 在更新currentIndex后添加
    updateTranslation();
  }

  void _handleKeyUp(KeyEvent event) {
    // 更新键盘状态
    String? keyLabel = keyMapping[event.logicalKey];
    if (keyLabel != null) {
      keyStates[keyLabel] = false;
      // 同步特殊键状态
      if (keyLabel == 'SHIFT') keyStates['SHIFT'] = false;
      if (keyLabel == 'CTRL') keyStates['CTRL'] = false;
      if (keyLabel == 'ALT') keyStates['ALT'] = false;
    }
  }

  String? _getCharFromKey(LogicalKeyboardKey key) {
    // 获取按键对应的字符
    if (key == LogicalKeyboardKey.keyG) return 'g';
    if (key == LogicalKeyboardKey.keyO) return 'o';
    if (key == LogicalKeyboardKey.keyD) return 'd';
    if (key == LogicalKeyboardKey.space) return ' ';
    // 添加所有字母键的映射
    if (key == LogicalKeyboardKey.keyA) return 'a';
    if (key == LogicalKeyboardKey.keyB) return 'b';
    if (key == LogicalKeyboardKey.keyC) return 'c';
    if (key == LogicalKeyboardKey.keyE) return 'e';
    if (key == LogicalKeyboardKey.keyF) return 'f';
    if (key == LogicalKeyboardKey.keyH) return 'h';
    if (key == LogicalKeyboardKey.keyI) return 'i';
    if (key == LogicalKeyboardKey.keyJ) return 'j';
    if (key == LogicalKeyboardKey.keyK) return 'k';
    if (key == LogicalKeyboardKey.keyL) return 'l';
    if (key == LogicalKeyboardKey.keyM) return 'm';
    if (key == LogicalKeyboardKey.keyN) return 'n';
    if (key == LogicalKeyboardKey.keyP) return 'p';
    if (key == LogicalKeyboardKey.keyQ) return 'q';
    if (key == LogicalKeyboardKey.keyR) return 'r';
    if (key == LogicalKeyboardKey.keyS) return 's';
    if (key == LogicalKeyboardKey.keyT) return 't';
    if (key == LogicalKeyboardKey.keyU) return 'u';
    if (key == LogicalKeyboardKey.keyV) return 'v';
    if (key == LogicalKeyboardKey.keyW) return 'w';
    if (key == LogicalKeyboardKey.keyX) return 'x';
    if (key == LogicalKeyboardKey.keyY) return 'y';
    if (key == LogicalKeyboardKey.keyZ) return 'z';
    if (key == LogicalKeyboardKey.comma) return ',';
    if (key == LogicalKeyboardKey.period) return '.';
    if (key == LogicalKeyboardKey.quote) return '\'';
    if (key == LogicalKeyboardKey.semicolon) return ':';
    return null;
  }

  void _generateNewText() {
    // 从CET4词汇表中获取单词并控制特殊符号的出现频率
    String newText = '';
    int wordCount = 0;
    int wordsUntilPunctuation = Random().nextInt(8) + 3; // 3-10个单词后出现标点
    int currentWordCount = 0;

    while (wordCount < 20) {  // 限制为20个单词
      if (currentWordCount >= wordsUntilPunctuation && wordCount < 19) {  // 确保最后一个不是标点
        // 添加标点符号
        final random = Random().nextInt(3);
        switch (random) {
          case 0:
            newText += ', ';
            break;
          case 1:
            newText += '. ';
            break;
          case 2:
            newText += ': ';
            break;
        }
        wordCount++; // 标点符号算作一个单词
        currentWordCount = 0;
        wordsUntilPunctuation = Random().nextInt(8) + 3; // 重置下一个标点出现的间隔
      } else {
        // 添加普通单词
        if (newText.isNotEmpty) {
          newText += ' ';
        }
        newText += WordService.getRandomWords(1);
        wordCount++;
        currentWordCount++;
      }
    }
    
    debugPrint('Generated new text: $newText');
    
    // 更新状态
    targetText.value = newText;
    currentIndex.value = 0;
    typedCharacters.clear();
    typedCharacters.addAll(List.filled(newText.length, false));
    errorCharacters.clear();
    errorCharacters.addAll(List.filled(newText.length, false));
  }

  void nextTheme() {
    currentThemeIndex.value = (currentThemeIndex.value + 1) % theme.themes.length;
  }

  void resetTypingPractice() {
    _generateNewText();
  }

  void updateTranslation() {
    if (currentIndex.value < targetText.value.length) {
      final translation = TranslationService.getCurrentWordTranslation(
        targetText.value,
        currentIndex.value
      );
      currentTranslation.value = translation ?? '';
    } else {
      currentTranslation.value = '';
    }
  }

  // 添加方法来更新翻译提示的位置
  void updateTranslationPosition(double x, double y) {
    translationX.value = x.toInt();
    translationY.value = y.toInt();
  }

  // 键名映射表
  final Map<LogicalKeyboardKey, String> keyMapping = {
    LogicalKeyboardKey.escape: 'ESC',
    LogicalKeyboardKey.f1: 'F1',
    LogicalKeyboardKey.f2: 'F2',
    LogicalKeyboardKey.f3: 'F3',
    LogicalKeyboardKey.f4: 'F4',
    LogicalKeyboardKey.f5: 'F5',
    LogicalKeyboardKey.f6: 'F6',
    LogicalKeyboardKey.f7: 'F7',
    LogicalKeyboardKey.f8: 'F8',
    LogicalKeyboardKey.f9: 'F9',
    LogicalKeyboardKey.f10: 'F10',
    LogicalKeyboardKey.f11: 'F11',
    LogicalKeyboardKey.f12: 'F12',
    LogicalKeyboardKey.printScreen: 'PRT\nSC',
    LogicalKeyboardKey.scrollLock: 'SCR\nLK',
    LogicalKeyboardKey.pause: 'PAUSE',
    
    LogicalKeyboardKey.backquote: '`',
    LogicalKeyboardKey.digit1: '1',
    LogicalKeyboardKey.digit2: '2',
    LogicalKeyboardKey.digit3: '3',
    LogicalKeyboardKey.digit4: '4',
    LogicalKeyboardKey.digit5: '5',
    LogicalKeyboardKey.digit6: '6',
    LogicalKeyboardKey.digit7: '7',
    LogicalKeyboardKey.digit8: '8',
    LogicalKeyboardKey.digit9: '9',
    LogicalKeyboardKey.digit0: '0',
    LogicalKeyboardKey.minus: '-',
    LogicalKeyboardKey.equal: '=',
    LogicalKeyboardKey.backspace: '←',
    LogicalKeyboardKey.insert: 'INS',
    LogicalKeyboardKey.home: 'HOME',
    LogicalKeyboardKey.pageUp: 'PGUP',
    
    LogicalKeyboardKey.tab: 'TAB',
    LogicalKeyboardKey.keyQ: 'Q',
    LogicalKeyboardKey.keyW: 'W',
    LogicalKeyboardKey.keyE: 'E',
    LogicalKeyboardKey.keyR: 'R',
    LogicalKeyboardKey.keyT: 'T',
    LogicalKeyboardKey.keyY: 'Y',
    LogicalKeyboardKey.keyU: 'U',
    LogicalKeyboardKey.keyI: 'I',
    LogicalKeyboardKey.keyO: 'O',
    LogicalKeyboardKey.keyP: 'P',
    LogicalKeyboardKey.bracketLeft: '[',
    LogicalKeyboardKey.bracketRight: ']',
    LogicalKeyboardKey.backslash: '\\',
    LogicalKeyboardKey.delete: 'DEL',
    LogicalKeyboardKey.end: 'END',
    LogicalKeyboardKey.pageDown: 'PGDN',
    
    LogicalKeyboardKey.capsLock: 'CAPS',
    LogicalKeyboardKey.keyA: 'A',
    LogicalKeyboardKey.keyS: 'S',
    LogicalKeyboardKey.keyD: 'D',
    LogicalKeyboardKey.keyF: 'F',
    LogicalKeyboardKey.keyG: 'G',
    LogicalKeyboardKey.keyH: 'H',
    LogicalKeyboardKey.keyJ: 'J',
    LogicalKeyboardKey.keyK: 'K',
    LogicalKeyboardKey.keyL: 'L',
    LogicalKeyboardKey.enter: 'ENTER',
    
    LogicalKeyboardKey.shiftLeft: 'SHIFT',
    LogicalKeyboardKey.keyZ: 'Z',
    LogicalKeyboardKey.keyX: 'X',
    LogicalKeyboardKey.keyC: 'C',
    LogicalKeyboardKey.keyV: 'V',
    LogicalKeyboardKey.keyB: 'B',
    LogicalKeyboardKey.keyN: 'N',
    LogicalKeyboardKey.keyM: 'M',
    LogicalKeyboardKey.slash: '/',
    LogicalKeyboardKey.shiftRight: 'SHIFT',
    
    LogicalKeyboardKey.controlLeft: 'CTRL',
    LogicalKeyboardKey.metaLeft: 'WIN',
    LogicalKeyboardKey.altLeft: 'ALT',
    LogicalKeyboardKey.space: '',  // Space bar
    LogicalKeyboardKey.altRight: 'ALT',
    LogicalKeyboardKey.controlRight: 'CTRL',
    LogicalKeyboardKey.arrowLeft: '←',
    LogicalKeyboardKey.arrowDown: '↓',
    LogicalKeyboardKey.arrowRight: '→',
    LogicalKeyboardKey.arrowUp: '↑',

    // 数字键盘
    LogicalKeyboardKey.numLock: 'NUM',
    LogicalKeyboardKey.numpadDivide: '/',
    LogicalKeyboardKey.numpadMultiply: '*',
    LogicalKeyboardKey.numpadSubtract: '-',
    LogicalKeyboardKey.numpad7: '7',
    LogicalKeyboardKey.numpad8: '8',
    LogicalKeyboardKey.numpad9: '9',
    LogicalKeyboardKey.numpadAdd: '+',
    LogicalKeyboardKey.numpad4: '4',
    LogicalKeyboardKey.numpad5: '5',
    LogicalKeyboardKey.numpad6: '6',
    LogicalKeyboardKey.numpad1: '1',
    LogicalKeyboardKey.numpad2: '2',
    LogicalKeyboardKey.numpad3: '3',
    LogicalKeyboardKey.numpad0: '0',
    LogicalKeyboardKey.numpadDecimal: '.',
  };

  String? _getKeyLabel(LogicalKeyboardKey key) {
    return keyMapping[key];
  }

  String? _getCharFromRawKey(LogicalKeyboardKey key) {
    // 获取按键对应的字符
    if (key == LogicalKeyboardKey.keyG) return 'g';
    if (key == LogicalKeyboardKey.keyO) return 'o';
    if (key == LogicalKeyboardKey.keyD) return 'd';
    if (key == LogicalKeyboardKey.space) return ' ';
    // 添加所有字母键的映射
    if (key == LogicalKeyboardKey.keyA) return 'a';
    if (key == LogicalKeyboardKey.keyB) return 'b';
    if (key == LogicalKeyboardKey.keyC) return 'c';
    if (key == LogicalKeyboardKey.keyE) return 'e';
    if (key == LogicalKeyboardKey.keyF) return 'f';
    if (key == LogicalKeyboardKey.keyH) return 'h';
    if (key == LogicalKeyboardKey.keyI) return 'i';
    if (key == LogicalKeyboardKey.keyJ) return 'j';
    if (key == LogicalKeyboardKey.keyK) return 'k';
    if (key == LogicalKeyboardKey.keyL) return 'l';
    if (key == LogicalKeyboardKey.keyM) return 'm';
    if (key == LogicalKeyboardKey.keyN) return 'n';
    if (key == LogicalKeyboardKey.keyP) return 'p';
    if (key == LogicalKeyboardKey.keyQ) return 'q';
    if (key == LogicalKeyboardKey.keyR) return 'r';
    if (key == LogicalKeyboardKey.keyS) return 's';
    if (key == LogicalKeyboardKey.keyT) return 't';
    if (key == LogicalKeyboardKey.keyU) return 'u';
    if (key == LogicalKeyboardKey.keyV) return 'v';
    if (key == LogicalKeyboardKey.keyW) return 'w';
    if (key == LogicalKeyboardKey.keyX) return 'x';
    if (key == LogicalKeyboardKey.keyY) return 'y';
    if (key == LogicalKeyboardKey.keyZ) return 'z';
    if (key == LogicalKeyboardKey.comma) return ',';
    if (key == LogicalKeyboardKey.period) return '.';
    if (key == LogicalKeyboardKey.quote) return '\'';
    if (key == LogicalKeyboardKey.semicolon) return ':';
    return null;
  }

  void _handleCharacterInput(String char) {
    if (currentIndex.value < targetText.value.length) {
      if (char.toLowerCase() == targetText.value[currentIndex.value].toLowerCase()) {
        // 输入正确
        typedCharacters[currentIndex.value] = true;
        errorCharacters[currentIndex.value] = false;
      } else {
        // 输入错误
        typedCharacters[currentIndex.value] = false;
        errorCharacters[currentIndex.value] = true;
      }
      
      typedCharacters.refresh();
      errorCharacters.refresh();
      currentIndex.value++;
      
      // 如果当前文本已经完成，生成新的文本
      if (currentIndex.value >= targetText.value.length) {
        _generateNewText();
      }
      
      updateTranslation();
    }
  }
}